package com.hf.tcpdemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServeThread extends Thread{

    @Override
    public void run() {
        try {
        //服务器ServerSocket
            ServerSocket serverSocket = new ServerSocket(9902);
            //死循环
            while (true){
                //创建用于接收客户端的Socket
                Socket socket = serverSocket.accept();
                //使用Socket和的客户端进行通信
                //---接收消息-----------------
                //获取输入流的对象
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(),"UTF-8"));
                //读取信息
                while(true) {
                    String str = bufferedReader.readLine();
                    //规定结束符
                    if (str != null && !str.equals("eof")){
                        //业务逻辑处理
                        System.out.println("服务器:"+str);
                    }else {
                        //终止循环读取信息
                        break;
                    }
                }
                //获取输出流对象
                BufferedWriter bufferedWriter = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
//发生消息
                String strMsg = "已接收";
                System.out.println("服务器："+strMsg);
                bufferedWriter.write(strMsg);
                //相当于一个换行符
                bufferedWriter.newLine();
                //自定义通信协议：消息发送使用 eof 作为结束标志位
                bufferedWriter.write("eof");
                bufferedWriter.write("\n");
                //清空输出流的发送区域，将信息发送到网络上
                bufferedWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
